<template>
  <a-modal
    :visible="visible"
    :title="formData.isEdit ? '编辑' : '新增'"
    cancelText="取消"
    okText="提交"
    @ok="submit"
    @cancel="cancel"
  >
    <a-form
      ref="formRef"
      :labelCol="labelCol"
      :wrapperCol="wrapperCol"
      :model="formData"
      :rules="formRules"
    >
      <a-form-item
        v-for="item in formColumn"
        :key="item.prop"
        :label="item.label"
        :name="item.prop"
      >
        <!-- 文本框 -->
        <a-textarea
          v-if="item.ele === 'textarea'"
          v-model:value="formData[item.prop]"
        ></a-textarea>
        <!-- input -->
        <a-input
          v-if="item.ele === 'input'"
          v-model:value="formData[item.prop]"
        >
        </a-input>
        <!-- 日期 -->
        <a-date-picker
          @change="onDateChange"
          style="width: 100%"
          v-if="item.ele === 'datePicker'"
          v-model:value="formData[item.prop]"
        ></a-date-picker>
        <!-- 下拉 -->
        <a-select
          v-if="item.ele === 'select'"
          v-model:value="formData[item.prop]"
        >
          <a-select-option
            v-for="it in item.selectOpts"
            :key="it.value"
            :value="it.value"
            >{{ it.name }}</a-select-option
          >
        </a-select>
        <!-- 上传 -->
        <a-upload
          v-if="item.ele === 'upload'"
          :file-list="fileList"
          :remove="handleRemove"
          :before-upload="beforeUpload"
        >
          <a-button>
            <upload-outlined></upload-outlined>
            点击上传
          </a-button>
        </a-upload>
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script setup>
import { message } from "ant-design-vue";
import { defineProps, defineEmits, ref, watch } from "vue";
import {
  sjbgSaveOrUpdate,
  sjbgUpload,
} from "@/api/module/constructAndImplement";
import global from "../../../global/global.vue";

const props = defineProps({
  visible: Boolean,
  editData: Object,
});
const emits = defineEmits(["close"]);

// 项目id
const projectId = global.xmid;

const labelCol = { span: 7 };
const wrapperCol = { span: 17 };

// 表单数据
const formData = ref({
  bgnr: "",
  time: "",
  dtzzcdyx: "",
  pfdw: "",
  bz: "",
  lx: "",
  approvalDocument: "",
});

// 监听传递的编辑数据
watch(
  () => props.editData,
  (newV, oldV) => {
    formData.value = Object.assign({}, newV);
    if (newV.pfFile) {
      fileList.value = [
        {
          name: newV.pfFileName,
          id: newV.pfFile,
        },
      ];
      pfFile.value = newV.pfFile;
    }
  },
  { deep: true }
);

// 选择日期
const onDateChange = (date, dateString) => {
  formData.value.time = dateString;
};

// 文件上传
const pfFile = ref("");
const fileList = ref([]);
// 上传列表的删除
const handleRemove = (file) => {
  const index = fileList.value.indexOf(file);
  const newFileList = fileList.value.slice();
  newFileList.splice(index, 1);
  fileList.value = newFileList;
  pfFile.value = "";
};
// 上传之前操作
const beforeUpload = (file) => {
  // 判断文件类型
  const allowedType = [
    "application/pdf",
    "application/msword",
    "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
    "application/vnd.ms-excel",
    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
  ];
  const isType = allowedType.includes(file.type);
  if (!isType) {
    return message.error("请选择正确的文件类型!");
  }
  // 限制只上传一个
  fileList.value = [file];
  pfFile.value = ''
  return false;
};

// 表单实例
const formRef = ref();

// 表单渲染规则
const formColumn = ref([
  { ele: "datePicker", label: "时间", prop: "time" },
  { ele: "textarea", label: "变更内容", prop: "bgnr" },
  { ele: "textarea", label: "对投资造成的影响", prop: "dtzzcdyx" },
  { ele: "input", label: "批复单位", prop: "pfdw" },
  { ele: "input", label: "备注", prop: "bz" },
  {
    ele: "select",
    label: "类型",
    prop: "lx",
    selectOpts: [
      { name: "一般", value: "0" },
      { name: "重大", value: "1" },
    ],
  },
  { ele: "upload", label: "批复文件", prop: "approvalDocument" },
]);

// 表单校验规则
const approvalValidator = (rule, value, callback) => {
  if (fileList.value.length === 0) {
    callback(new Error("请上传文件"));
  } else {
    callback();
  }
};
const formRules = {
  bgnr: [{ required: true, message: "请输入", trigger: "blur" }],
  time: [{ required: true, message: "请选择", trigger: "change" }],
  dtzzcdyx: [{ required: true, message: "请输入", trigger: "blur" }],
  pfdw: [{ required: true, message: "请输入", trigger: "blur" }],
  bz: [{ required: true, message: "请输入", trigger: "blur" }],
  lx: [{ required: true, message: "请选择", trigger: "blur" }],
  approvalDocument: [{ validator: approvalValidator, trigger: "blur" }],
};

// 数据清空
const clearFormData = () => {
  formData.value.bgnr = "";
  formData.value.time = "";
  formData.value.dtzzcdyx = "";
  formData.value.pfdw = "";
  formData.value.bz = "";
  formData.value.lx = "";
  formData.value.approvalDocument = "";
  formData.value.isEdit = false;
  fileList.value = [];
};

// 点击提交
const submit = async () => {
  await formRef.value.validate();
  // 上传接口
  if (!pfFile.value) {
    const formDataData = new FormData();
    formDataData.append("file", fileList.value[0]);
    const res = await sjbgUpload(formDataData);
    pfFile.value = res.data.id;
  }
  // 提交接口
  await sjbgSaveOrUpdate({
    bgnr: formData.value.bgnr,
    bz: formData.value.bz,
    dtzzcdyx: formData.value.dtzzcdyx,
    id: formData.value.id,
    lx: formData.value.lx,
    pfFile: pfFile.value,
    pfdw: formData.value.pfdw,
    time: formData.value.time,
    xmid: projectId,
  });
  message.success("上传成功");
  clearFormData();
  formRef.value.clearValidate();
  emits("close", false);
};

const cancel = () => {
  clearFormData();
  formRef.value.clearValidate();
  emits("close", false);
};

const tokenKey = localStorage.getItem("token_key");
const token = localStorage.getItem("token");

const headers = {
  Authorization: token,
  "Authorization-key": tokenKey,
};
</script>
